import { DirectiveBinding } from '@vue/runtime-core'

let listener: () => void = function () {
  console.log('listener')
}
let element: Element | Document = document.createElement('div')
let timer: undefined | number = undefined

export default {
  mounted(el: Element, binding: DirectiveBinding) {
    const hasBindBody = binding.arg === 'body'
    const distance = Number(el.getAttribute('scroll-distance')) || 100
    element = hasBindBody ? document : el
    let throttle = true

    listener = function (this: Element) {
      const scrollTop = hasBindBody
        ? document.documentElement.scrollTop
        : this.scrollTop
      const scrollHeight = hasBindBody
        ? document.documentElement.scrollHeight
        : this.scrollHeight
      const clientHeight = hasBindBody
        ? document.documentElement.clientHeight
        : this.clientHeight
      const scrollDistance = scrollHeight - scrollTop - clientHeight
      if (scrollDistance <= distance && throttle) {
        throttle = false
        binding.value()
        timer = setTimeout(() => {
          throttle = true
        }, 50)
      }
    }
    element.addEventListener('scroll', listener)
  },
  beforeUnmount(el: Element, binding: DirectiveBinding) {
    clearTimeout(timer)
    element.removeEventListener('scroll', listener)
  },
}
